package com.xtone.pm.detector;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class URLConnectionUtil {
	private final static  String SERVLET_GET = "GET";
	private final static  String SERVLET_POST = "POST";

	
	public static String prepareParam(Map<String, Object> paramMap){
		StringBuffer sb = new StringBuffer();
		if(paramMap ==null || paramMap.isEmpty()){
			return "";
		}else{
			for (String key : paramMap.keySet()) {
				String value = (String) paramMap.get(key);
				if(sb.length()<1){
					sb.append(key).append("=").append(value);
				}else{
					sb.append("&").append(key).append("=").append(value);
				}
			}
		}
		return sb.toString();
	}
	public static String doGet(String urlStr,Map<String, Object> paramMap) throws Exception{
		String result = "";
		String paramStr = prepareParam(paramMap);
		if(paramStr==null||paramStr.length()<1){
			
		}else{
			urlStr+="?"+paramStr;
		}
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(SERVLET_GET);
		conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
		conn.connect();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while((line = reader.readLine())!=null){
			result = "\n"+line;
		}
		reader.close();
		return result;
	}
	public static String doPost(String urlStr,Map<String, Object> paramMap) throws Exception{
		String result = "";
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(SERVLET_POST);
		String paramStr = prepareParam(paramMap);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		OutputStream os = conn.getOutputStream();
		os.write(paramStr.toString().getBytes("UTF-8"));
		os.close();
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while((line = reader.readLine())!=null){
			result = "\n"+line;
		}
		reader.close();
		return result;
	}

	public static void main(String args[]) throws Exception{
		String url ="http://211.136.82.162:8011/HTcmccIvrSystem1.0/lottery/saveLottery";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("channelId", "123");
		paramMap.put("context", "测试");
		paramMap.put("issue", "12532");
		paramMap.put("inTime", "21111022");
		String result = URLConnectionUtil.doPost(url, paramMap);
		System.out.println(result);
	}
}
